﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.WindowsAPICodePack.Shell;
using System.IO;
using System.Threading;
using System.Diagnostics;
using ClipShow2.LibraryManager;
using ClipShow2.MediaTypes;
using ClipShow2.Storage;


namespace ClipShowShell.Code
{
    internal class Thumbs
    {
        private ClipShowContent _sourceLibrary;

        public Thumbs(ClipShowContent source)
        {
            _sourceLibrary = source;
        }

        public void Start()
        {
            Thread localExtract;
            localExtract = new Thread(new ThreadStart(Extract));
            localExtract.Name = "mce_ClipShow_ThumbnailExtraction";
            localExtract.IsBackground = false;
            localExtract.Priority = ThreadPriority.Normal;
            localExtract.Start();
        }
        private void Extract()
        {
            foreach (ClipShowMetadata item in _sourceLibrary.MediaItems)
            {
                if (!File.Exists(item.ThumbnailUrl))
                {
                    item.IsTempThumbnail = false;
                    try
                    {
                        // Many thanks to the Win7 team for the new Shell helper libs
                        ShellFile sf = ShellFile.FromFilePath(item.Url);
                        System.Drawing.Bitmap thumb = sf.Thumbnail.Bitmap;
                        thumb.Save(item.ThumbnailUrl);

                    }
                    catch (SystemException se)
                    {
                        Debug.WriteLine(String.Format("clipShow2.ExtractThumbs:{0}", se.Message));
                    }
                }
                if (item.IsGroupItem)
                {
                    foreach (ClipShowMetadata childItem in item.GroupItems)
                    {
                        if (!File.Exists(childItem.ThumbnailUrl))
                        {
                            childItem.IsTempThumbnail = true;
                            try
                            {
                                ShellFile sf2 = ShellFile.FromFilePath(childItem.Url);
                                System.Drawing.Bitmap thumb2 = sf2.Thumbnail.Bitmap;
                                thumb2.Save(childItem.ThumbnailUrl);
                            }
                            catch (SystemException se)
                            {
                                Debug.WriteLine("clipShow2.ExtractThumbs:{0}", se.Message);
                            }
                        }
                    }
                }
            }
        }

    }
}
